package org.gnomus.util;

import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;

public class stdio {

    private static final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    public static void startCapture() {
        synchronized (baos) {
            if (System.out instanceof CapturedStream && System.err instanceof CapturedStream) {
                baos.reset();
            } else {
                System.setOut(new CapturedStream(System.out));
                System.setErr(new CapturedStream(System.err));
            }
        }
    }

    public static String getCaptureContent() {
        flush();
        String s = baos.toString();
        baos.reset();
        return s;
    }

    public static void flush() {
        System.err.flush();
        System.out.flush();
    }

    private static class CapturedStream extends PrintStream {

        private OutputStreamWriter osw;

        public CapturedStream(PrintStream ps) {
            super(ps, false);
            osw = new OutputStreamWriter(baos);
        }

        public void write(byte buf[], int off, int len) {
            synchronized (baos) {
                super.write(buf, off, len);
                baos.write(buf, off, len);
            }
        }

        public void write(int b) {
            synchronized (baos) {
                super.write(b);
                baos.write(b);
            }
        }

        public void println(String s) {
            super.println(s);
            flush();
        }
    }
}
